package com.yanqu.road.entity.activity.chefduel.rank;

import java.util.Comparator;
import java.util.LinkedList;

public class CampRankListModel {

    private Comparator<CampRank> rankSort = new CampRankSort();

    private LinkedList<CampRank> rankList = new LinkedList<>();

    public void rankChange(CampRank rank) {
        synchronized (this) {
            boolean change = false;
            boolean find = false;
            for (CampRank tmpRank : rankList) {
                // 找到了
                if (tmpRank.getId() == rank.getId()) {
                    tmpRank.setValue(rank.getValue());
                    tmpRank.setTime(rank.getTime());
                    change = true;
                    find = true;
                    break;
                }
            }
            if (!find) {
                rankList.add(rank);
                change = true;
            }
            if (change) {
                rankSort();
            }
        }
    }

    public LinkedList<CampRank> getRankList() {
        return new LinkedList<>(rankList);
    }

    public void setRankList(LinkedList<CampRank> rankList) {
        synchronized (this) {
            this.rankList = rankList;
            rankSort();
        }
    }

    public int getMyRank(int id) {
        int rank = -1;
        int index = 0;
        synchronized (this) {
            for(CampRank userRank : rankList){
                if(userRank.getId() == id){
                    rank = index + 1;
                    break;
                }
                index++;
            }
        }
        return rank;
    }

    /**
     * 排序，记得加锁
     */
    private void rankSort() {
        rankList.sort(rankSort);
    }

}
